package service

import (
	"errors"
	"gauss/internal/model"
	"gauss/internal/model/request"
	"gauss/internal/utils/db"
	"gauss/internal/utils/jwt"
	"golang.org/x/crypto/bcrypt"
)

// UserService 用户服务
type UserService struct{}

// Login 用户登录
func (s *UserService) Login(req *request.LoginRequest) (string, error) {
	var user model.User
	if err := db.DB.Where("username = ?", req.Username).First(&user).Error; err != nil {
		return "", errors.New("用户不存在")
	}

	if user.Status == 0 {
		return "", errors.New("用户已被禁用")
	}

	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)); err != nil {
		return "", errors.New("密码错误")
	}

	// 生成Token
	token, err := jwt.GenerateToken(user.ID, user.Username, user.RoleID)
	if err != nil {
		return "", err
	}

	return token, nil
}

// Register 用户注册
func (s *UserService) Register(req *request.RegisterRequest) error {
	var count int64
	db.DB.Model(&model.User{}).Where("username = ?", req.Username).Count(&count)
	if count > 0 {
		return errors.New("用户名已存在")
	}

	// 加密密码
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}

	user := model.User{
		Username: req.Username,
		Password: string(hashedPassword),
		Nickname: req.Nickname,
		Email:    req.Email,
		Phone:    req.Phone,
		Status:   1,
		RoleID:   2, // 默认为普通用户角色
	}

	return db.DB.Create(&user).Error
}

// GetUserInfo 获取用户信息
func (s *UserService) GetUserInfo(id uint) (*model.User, error) {
	var user model.User
	if err := db.DB.First(&user, id).Error; err != nil {
		return nil, errors.New("用户不存在")
	}
	return &user, nil
}

// UpdateUser 更新用户信息
func (s *UserService) UpdateUser(id uint, req *request.UpdateUserRequest) error {
	updates := make(map[string]interface{})

	if req.Nickname != "" {
		updates["nickname"] = req.Nickname
	}
	if req.Email != "" {
		updates["email"] = req.Email
	}
	if req.Phone != "" {
		updates["phone"] = req.Phone
	}
	if req.Avatar != "" {
		updates["avatar"] = req.Avatar
	}
	if req.Status != nil {
		updates["status"] = *req.Status
	}
	if req.RoleID != nil {
		updates["role_id"] = *req.RoleID
	}

	return db.DB.Model(&model.User{}).Where("id = ?", id).Updates(updates).Error
}

// UpdatePassword 更新密码
func (s *UserService) UpdatePassword(id uint, req *request.UpdatePasswordRequest) error {
	var user model.User
	if err := db.DB.First(&user, id).Error; err != nil {
		return errors.New("用户不存在")
	}

	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.OldPassword)); err != nil {
		return errors.New("原密码错误")
	}

	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost)
	if err != nil {
		return err
	}

	return db.DB.Model(&user).Update("password", string(hashedPassword)).Error
}

// ListUsers 获取用户列表
func (s *UserService) ListUsers(page, size int) ([]model.User, int64, error) {
	var users []model.User
	var total int64

	db.DB.Model(&model.User{}).Count(&total)
	if err := db.DB.Limit(size).Offset((page - 1) * size).Find(&users).Error; err != nil {
		return nil, 0, err
	}

	return users, total, nil
}

// DeleteUser 删除用户
func (s *UserService) DeleteUser(id uint) error {
	return db.DB.Delete(&model.User{}, id).Error
} 